package org.hibernate.test.dao;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Projections;
import org.hibernate.test.dto.RolDto;
import org.hibernate.test.dto.UserDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

@Repository("rolRepository")
@Transactional(propagation = Propagation.MANDATORY, readOnly = true)
public class RolDao implements IDAO<RolDto> {

	@Autowired
	private SessionFactory sessionFactory;
	
	@Override
	@SuppressWarnings("unchecked")
	public List<RolDto> listAll() {
		return getSession().createCriteria(UserDto.class).list();
	}

	@Override
	public RolDto getById(Long id) {
		return (RolDto) getSession().get(RolDto.class, id);
	}

	@Override
	public RolDto saveOrUpdate(RolDto rol) {
		if (rol.getId()!= 0L){
            getSession().merge(rol);
        } else {
            getSession().save(rol);
        }
        return rol;
	}

	@Override
	public void delete(RolDto rol) {
		getSession().delete(rol);
	}

	@Override
	public Integer count() {
		return (Integer) getSession().createCriteria(RolDto.class).setProjection(Projections.rowCount()).uniqueResult();
	}
	private Session getSession(){
        return sessionFactory.getCurrentSession();
    }

}
